var express = require("express");
var router = express.Router();
var { Article } = require("../../models");
var { Op } = require("sequelize");
const { NotFoundError, onSuccess, onError } = require("../../utils/response");

/**
 * 文章列表接口
 */
router.get("/articleList", async function (req, res, next) {
  try {
    const query = req.query;

    const pageSize = Math.abs(Number(query.pageSize)) || 10;
    const pageCount = Math.abs(Number(query.pageCount)) || 1;

    const offset = (pageCount - 1) * pageSize;

    const condition = {
      order: [["id", "ASC"]],
      limit: pageSize,
      offset,
    };
    if (query.title) {
      condition.where = {
        title: {
          [Op.like]: `%${query.title}%`,
        },
      };
    }
    const articleData = await Article.findAll(condition);
    onSuccess(res, "列表查询成功", articleData);
  } catch (error) {
    onError(res, error);
  }
});

/**
 * 文章详情接口
 */
router.get("/getArticleDetail", async function (req, res, next) {
  try {
    const { id } = req.query;
    const articleData = await Article.findOne({
      where: {
        id,
      },
    });
    if (articleData) {
      onSuccess(res, "文章详情查询成功", articleData);
    } else {
      throw new NotFoundError("文章不存在");
    }
  } catch (error) {
    onError(res, error);
  }
});

/**
 * 文章添加接口
 */
router.post("/addArticle", async function (req, res, next) {
  try {
    const { title, content } = req.body;
    const articleData = await Article.create({
      title,
      content,
    });
    if (articleData) {
      onSuccess(res, "文章添加成功", articleData);
    } else {
      throw new NotFoundError("文章不存在");
    }
  } catch (error) {
    onError(res, error);
  }
});

/**
 * 文章删除接口
 */
router.post("/deleteArticle", async function (req, res, next) {
  try {
    const { id } = req.body;
    const articleData = await Article.findOne({
      where: { id },
    });
    if (articleData) {
      await articleData.destroy();
      onSuccess(res, "文章删除成功");
    } else {
      throw new NotFoundError("文章不存在");
    }
  } catch (error) {
    onError(res, error);
  }
});

/**
 * 文章更新接口
 */
router.post("/updateArticle", async function (req, res, next) {
  try {
    const { id, title, content } = req.body;
    const articleData = await Article.findOne({
      where: { id },
    });
    if (articleData) {
      await articleData.update({
        title,
        content,
      });
      onSuccess(res, "文章更新成功");
    } else {
      throw new NotFoundError("文章不存在");
    }
  } catch (error) {
    onError(res, error);
  }
});

module.exports = router;
